package org.tiger.netty.server.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lwl
 * @date 2020/9/30 9:51 上午
 */
public class NioTestGatherAndScatter {

	private static Logger logger = LoggerFactory.getLogger(NioTestGatherAndScatter.class);

	public static void main(String[] args) throws Exception {

		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

		InetSocketAddress inetSocketAddress = new InetSocketAddress(8899);

		serverSocketChannel.socket().bind(inetSocketAddress);

		int maxLenth = 3 + 4 + 6;

		ByteBuffer[] byteBuffers = new ByteBuffer[3];

		byteBuffers[0] = ByteBuffer.allocate(3);
		byteBuffers[1] = ByteBuffer.allocate(4);
		byteBuffers[2] = ByteBuffer.allocate(6);

		SocketChannel socketChannel = serverSocketChannel.accept();

		while (true){

			int byteReads = 0;

			while (byteReads < maxLenth){
				long r = socketChannel.read(byteBuffers);
				byteReads += r;

				logger.info("byteReads : " + byteReads);

				Arrays.asList(byteBuffers).stream().map(byteBuffer -> {
					return "position:" + byteBuffer.position() + "****  limit:"
							+ byteBuffer.limit();
				}).forEach(entry -> logger.info(entry));

			}

			Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.flip());

			int byteWrite = 0;

			while (byteWrite < maxLenth){

				// 写出去
				long w = socketChannel.write(byteBuffers);
				byteWrite += w;

			}
			Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.clear());
			logger.info("bytesRead: " + byteReads + ", bytesWritten: " + byteWrite
					+ ", messageLength: " + maxLenth);

		}

	}

}
